package com.sddnytsh.body_buildingsystem.screens

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.List
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Divider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import com.sddnytsh.body_buildingsystem.data.state.UserState
import com.sddnytsh.body_buildingsystem.network.CommunityApiService
import com.sddnytsh.body_buildingsystem.topic.CommunityPostCreateRequest
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

@Composable
fun CreatePostScreen(navController: NavController) {
    var title by remember { mutableStateOf("") }
    var content by remember { mutableStateOf("") }
    var isPosting by remember { mutableStateOf(false) }
    var showErrorDialog by remember { mutableStateOf(false) }
    var errorMessage by remember { mutableStateOf("") }
    var showSuccessDialog by remember { mutableStateOf(false) }
    
    // 使用UserState中的用户ID
    val currentUserId = UserState.currentUserId ?: 1L

    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.White)
    ) {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(56.dp)
                .background(Color.White)
                .padding(horizontal = 16.dp),
            contentAlignment = Alignment.CenterStart
        ) {
            IconButton(
                onClick = { navController.popBackStack() },
                modifier = Modifier.align(Alignment.CenterStart)
            ) {
                Icon(
                    imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                    contentDescription = "返回"
                )
            }

            Text(
                text = "发布帖子",
                style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold),
                modifier = Modifier.align(Alignment.Center)
            )

            if (isPosting) {
                CircularProgressIndicator(
                    modifier = Modifier
                        .size(24.dp)
                        .align(Alignment.CenterEnd),
                    strokeWidth = 2.dp
                )
            } else {
                TextButton(
                    onClick = {
                        if (title.isBlank() || content.isBlank()) {
                            errorMessage = "请填写标题和内容"
                            showErrorDialog = true
                            return@TextButton
                        }
                        
                        isPosting = true
                        CoroutineScope(Dispatchers.Main).launch {
                            try {
                                val apiService = CommunityApiService()
                                val request = CommunityPostCreateRequest(
                                    userId = currentUserId,
                                    title = title.trim(),
                                    content = content.trim()
                                )
                                
                                val result = apiService.createPost(request)
                                result.fold(
                                    onSuccess = { post ->
                                        isPosting = false
                                        showSuccessDialog = true
                                    },
                                    onFailure = { exception ->
                                        isPosting = false
                                        errorMessage = exception.message ?: "发布失败，请重试"
                                        showErrorDialog = true
                                    }
                                )
                            } catch (e: Exception) {
                                isPosting = false
                                errorMessage = "网络错误，请检查网络连接"
                                showErrorDialog = true
                            }
                        }
                    },
                    enabled = title.isNotBlank() && content.isNotBlank() && !isPosting,
                    modifier = Modifier.align(Alignment.CenterEnd)
                ) {
                    Text("发布", color = Color(0xFF6200EE))
                }
            }
        }

        Divider(color = Color.LightGray, thickness = 0.5.dp)

        // 内容输入区域
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(16.dp)
        ) {
            OutlinedTextField(
                value = title,
                onValueChange = { title = it },
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = 16.dp),
                label = { Text("标题") },
                placeholder = { Text("请输入标题") },
                singleLine = true,
            )

            OutlinedTextField(
                value = content,
                onValueChange = { content = it },
                modifier = Modifier
                    .fillMaxWidth()
                    .weight(1f),
                label = { Text("内容") },
                placeholder = { Text("请输入内容...") },
                maxLines = Int.MAX_VALUE,
            )

            Spacer(modifier = Modifier.height(16.dp))

            // 添加图片按钮（可选功能）
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                IconButton(
                    onClick = { /* 添加图片逻辑 */ },
                    modifier = Modifier.size(48.dp)
                ) {
                    Icon(
                        imageVector = Icons.Default.List,
                        contentDescription = "添加图片",
                        tint = Color.Gray
                    )
                }
            }
        }
    }
    
    // 错误对话框
    if (showErrorDialog) {
        AlertDialog(
            onDismissRequest = { showErrorDialog = false },
            title = { Text("错误") },
            text = { Text(errorMessage) },
            confirmButton = {
                TextButton(onClick = { showErrorDialog = false }) {
                    Text("确定")
                }
            }
        )
    }
    
    // 成功对话框
    if (showSuccessDialog) {
        AlertDialog(
            onDismissRequest = { 
                showSuccessDialog = false
                navController.popBackStack()
            },
            title = { Text("成功") },
            text = { Text("帖子发布成功！") },
            confirmButton = {
                TextButton(onClick = { 
                    showSuccessDialog = false
                    navController.popBackStack()
                }) {
                    Text("确定")
                }
            }
        )
    }
}